<template>
  <div class="pet-details">
    <div class="container">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="!pet" class="error-container">
        <el-empty description="未找到宠物信息" />
        <el-button @click="$router.push('/pets')" type="primary" class="mt-3">
          返回宠物列表
        </el-button>
      </div>
      
      <template v-else>
        <div class="back-link mb-3">
          <router-link to="/pets">
            <i class="el-icon-arrow-left"></i> 返回宠物列表
          </router-link>
        </div>
        
        <div class="pet-container">
          <div class="pet-image-container">
            <PetImage :src="pet.image_url" :alt="pet.name" class="pet-detail-image" />
            <span v-if="pet.is_adopted" class="adopted-badge">已领养</span>
          </div>
          
          <div class="pet-info-container">
            <h1 class="pet-name">{{ pet.name }}
              <span class="pet-gender" :class="{'male': pet.gender === 'male', 'female': pet.gender === 'female'}">
                {{ formatGender(pet.gender) }}
              </span>
            </h1>
            
            <div class="pet-meta">
              <div class="meta-item">
                <span class="meta-label">类别:</span>
                <span class="meta-value">{{ getCategoryName(pet.category_id) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">品种:</span>
                <span class="meta-value">{{ pet.breed || '未知' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">年龄:</span>
                <span class="meta-value">{{ formatAge(pet.age) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">大小:</span>
                <span class="meta-value">{{ formatSize(pet.size) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">健康状况:</span>
                <span class="meta-value">{{ pet.health || '良好' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">领养状态:</span>
                <span class="meta-value" :class="{'text-success': !pet.is_adopted, 'text-danger': pet.is_adopted}">
                  {{ pet.is_adopted ? '已领养' : '待领养' }}
                </span>
              </div>
              <div class="meta-item" v-if="pet.created_at">
                <span class="meta-label">加入时间:</span>
                <span class="meta-value">{{ formatDate(pet.created_at) }}</span>
              </div>
            </div>
            
            <div class="pet-description mt-4">
              <h3>宠物描述</h3>
              <p>{{ pet.description || '暂无描述' }}</p>
            </div>
            
            <div class="pet-actions mt-4">
              <el-button
                v-if="!pet.is_adopted && isLoggedIn"
                type="primary"
                size="large"
                @click="applyForAdoption"
              >
                申请领养
              </el-button>
              
              <el-button
                v-if="!pet.is_adopted && !isLoggedIn"
                type="primary"
                size="large"
                @click="redirectToLogin"
              >
                登录后申请领养
              </el-button>
              
              <el-button
                v-if="pet.is_adopted"
                type="info"
                size="large"
                disabled
              >
                已被领养
              </el-button>
              <!-- 评论按钮 -->
              <el-button
                type="success"
                size="large"
                @click="showCommentDialog = true"
                v-if="isLoggedIn"
              >
                评论
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="pet-details-section mt-5">
          <el-tabs>
            <el-tab-pane label="详细介绍" name="details">
              <div class="pet-long-description">
                <h3>更多关于 {{ pet.name }} 的信息</h3>
                <p>{{ pet.long_description || pet.description || '暂无更多详细介绍' }}</p>
              </div>
              
              <div class="pet-requirements mt-4" v-if="pet.requirements">
                <h3>领养要求</h3>
                <p>{{ pet.requirements }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="领养须知" name="adoption">
              <div class="adoption-guide">
                <h3>领养须知</h3>
                <ol>
                  <li>必须年满18周岁，有稳定的生活来源和住所</li>
                  <li>必须尊重生命，承诺善待宠物，不遗弃，不虐待</li>
                  <li>必须有足够的时间和精力照顾宠物</li>
                  <li>必须保证宠物得到必要的疫苗接种和医疗保障</li>
                  <li>必须同意平台不定期回访，确保宠物健康生活</li>
                </ol>
              </div>
              
              <div class="adoption-process mt-4">
                <h3>领养流程</h3>
                <ol>
                  <li>提交领养申请表</li>
                  <li>等待平台审核（1-3个工作日）</li>
                  <li>审核通过后，安排线下见面</li>
                  <li>签署领养协议</li>
                  <li>带宠物回家</li>
                </ol>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 评论弹窗表单 -->
        <el-dialog v-model="showCommentDialog" title="发表评论" width="400px">
          <el-form :model="commentForm">
            <el-form-item label="评分">
              <el-rate v-model="commentForm.rating" />
            </el-form-item>
            <el-form-item label="评论内容">
              <el-input
                type="textarea"
                v-model="commentForm.comment"
                placeholder="请输入您的评论"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showCommentDialog = false">取消</el-button>
            <el-button type="primary" @click="submitComment">提交</el-button>
          </template>
        </el-dialog>
        <!-- 评论列表 -->
        <div class="pet-comments mt-5">
          <h3>用户评论</h3>
          <el-empty v-if="comments.length === 0" description="暂无评论" />
          <el-card v-for="item in comments" :key="item.id" class="comment-item">
            <div>
              <strong>{{ item.username }}</strong>
              <el-rate :model-value="item.rating" disabled />
              <span class="comment-date">{{ formatDate(item.created_at) }}</span>
            </div>
            <div>{{ item.comment }}</div>
          </el-card>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import { getImageUrl } from '@/utils/image';
import PetImage from '@/components/pets/PetImage.vue';
import axios from 'axios';

export default {
  name: 'PetDetails',
  components: {
    PetImage
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loadingPet: false,
      showCommentDialog: false,
      commentForm: {
        rating: 0,
        comment: ''
      },
      comments: []
    };
  },
  computed: {
    ...mapGetters({
      pet: 'pets/getPet',
      loading: 'isLoading',
      categories: 'categories/allCategories',
      isLoggedIn: 'auth/isAuthenticated'
    }),
    petImageUrl() {
      if (!this.pet) {
        return 'https://via.placeholder.com/600x400?text=No+Image';
      }
      return getImageUrl(this.pet.image_url, 'https://via.placeholder.com/600x400?text=No+Image');
    }
  },
  async created() {
    // 确保类别数据已加载
    if (this.categories.length === 0) {
      await this.fetchCategories();
    }
    
    // 获取宠物详情
    await this.fetchPet(this.id);
    // 获取评论
    await this.fetchComments();
  },
  methods: {
    ...mapActions({
      fetchPet: 'pets/fetchPet',
      fetchCategories: 'categories/fetchCategories'
    }),
    async fetchComments() {
      try {
        const res = await axios.get(`/api/petcomments/${this.id}`);
        this.comments = res.data;
      } catch (e) {
        this.comments = [];
      }
    },
    async submitComment() {
      const token = sessionStorage.getItem('token');
      if (!token) {
        this.$message.error('请先登录');
        return;
      }
      if (!this.commentForm.comment || !this.commentForm.rating) {
        this.$message.error('请填写评论内容和评分');
        return;
      }
      try {
        await axios.post('/api/petcomments', {
          pet_id: this.id,
          rating: this.commentForm.rating,
          comment: this.commentForm.comment
        }, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        this.$message.success('评论成功');
        this.showCommentDialog = false;
        this.commentForm.rating = 0;
        this.commentForm.comment = '';
        this.fetchComments();
      } catch (e) {
        this.$message.error('评论失败');
      }
    },
    formatGender(gender) {
      const genderMap = {
        'male': '公',
        'female': '母',
        'unknown': '未知'
      };
      return genderMap[gender] || '未知';
    },
    formatAge(age) {
      if (!age) return '未知';
      return `${age} 岁`;
    },
    formatSize(size) {
      const sizeMap = {
        'small': '小型',
        'medium': '中型',
        'large': '大型',
        'unknown': '未知'
      };
      return sizeMap[size] || '未知';
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    getCategoryName(categoryId) {
      if (!categoryId) return '未知';
      const category = this.categories.find(c => c.id === categoryId);
      return category ? category.name : '未知';
    },
    applyForAdoption() {
      this.$router.push(`/pets/${this.id}/adopt`);
    },
    redirectToLogin() {
      this.$router.push(`/login?redirect=/pets/${this.id}/adopt`);
    }
  }
}
</script>

<style lang="scss" scoped>
.pet-details {
  padding: 40px 0;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.back-link {
  a {
    color: var(--primary-color);
    display: inline-flex;
    align-items: center;
    
    i {
      margin-right: 5px;
    }
  }
}

.pet-container {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pet-image-container {
  flex: 1;
  min-width: 300px;
  position: relative;
}

.pet-image {
  width: 100%;
  height: 100%;
  min-height: 400px;
  object-fit: cover;
}

.adopted-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.9rem;
  font-weight: bold;
}

.pet-info-container {
  flex: 1;
  min-width: 300px;
  padding: 20px;
}

.pet-name {
  font-size: 2rem;
  margin-bottom: 20px;
  color: var(--secondary-color);
  display: flex;
  align-items: center;
}

.pet-gender {
  margin-left: 10px;
  font-size: 1rem;
  padding: 3px 10px;
  border-radius: 15px;
  color: white;
  font-weight: bold;
  
  &.male {
    background-color: #409eff;
  }
  
  &.female {
    background-color: #f56c6c;
  }
}

.pet-meta {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.meta-item {
  display: flex;
}

.meta-label {
  font-weight: bold;
  width: 80px;
  color: var(--gray-color);
}

.meta-value {
  flex-grow: 1;
}

.pet-actions {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
}

.pet-details-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

@media (max-width: 768px) {
  .pet-container {
    flex-direction: column;
  }
  
  .pet-image {
    min-height: 300px;
  }
}
</style> 